package com.xxl.job.admin.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xxl.job.admin.core.model.XxlJobLogReport;
import com.xxl.job.admin.dao.XxlJobLogReportDao;
import com.xxl.job.admin.service.XxlJobLogReportService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.sum;
import static com.xxl.job.admin.core.model.table.Tables.XXL_JOB_LOG_REPORT;

@Service
public class XxlJobLogReportServiceImpl extends ServiceImpl<XxlJobLogReportDao, XxlJobLogReport> implements XxlJobLogReportService {

//    UPDATE xxl_job_log_report
//    SET `running_count` = #{runningCount},
//            `suc_count` = #{sucCount},
//            `fail_count` = #{failCount}
//    WHERE `trigger_day` = #{triggerDay}
    @Override
    public int updateByTriggerDay(XxlJobLogReport xxlJobLogReport) {
      boolean i =  UpdateChain.of(XxlJobLogReport.class)
                .set(XXL_JOB_LOG_REPORT.RUNNING_COUNT,xxlJobLogReport.getRunningCount())
                .set(XXL_JOB_LOG_REPORT.SUC_COUNT,xxlJobLogReport.getSucCount())
                .set(XXL_JOB_LOG_REPORT.FAIL_COUNT,xxlJobLogReport.getFailCount())
                .where(XXL_JOB_LOG_REPORT.TRIGGER_DAY.eq(xxlJobLogReport.getTriggerDay())).update();
      return i?1:0;
    }

    @Override
    public XxlJobLogReport queryLogReportTotal() {
        QueryWrapper q=QueryWrapper.create()
                .select(sum(XXL_JOB_LOG_REPORT.RUNNING_COUNT).as("running_count"),
                        sum(XXL_JOB_LOG_REPORT.SUC_COUNT).as("suc_count"),
                        sum(XXL_JOB_LOG_REPORT.FAIL_COUNT).as("fail_count"))
                .from(XXL_JOB_LOG_REPORT);
        return getOne(q);
    }

    @Override
    public List<XxlJobLogReport> queryLogReport(Date startDate, Date endDate) {
        QueryWrapper q=QueryWrapper.create()
                .from(XXL_JOB_LOG_REPORT)
                .where(XXL_JOB_LOG_REPORT.TRIGGER_DAY.between(startDate,endDate))
                .orderBy(XXL_JOB_LOG_REPORT.TRIGGER_DAY.asc());
        return list(q);
    }
}
